
function Game(el) {

    // 保存地图对象
    this.el = document.querySelector(el)

    // 创建地图
    this.map = new Map(this.el) //将地图标签对象传递给map构造函数，里面设置宽高等
    this.map.create() 

    // 创建食物
    this.food = new Food(this.el) // 将地图传给视图构造函数，后期追加食物
    this.food.create() 

    // 创建蛇
    this.snake = new Snake(this.el) 
    this.snake.create() 

    this.t = null
}

Game.prototype.start = function(){
    clearInterval(this.t)
   this.t= setInterval(()=>{
        
        this.snake.move() 
        
        let snakeX = this.snake.snakeObj[0].x * 20
        let snakeY = this.snake.snakeObj[0].y * 20
        let foodX = this.food.foodX
        let foodY = this.food.foodY
      
        if (snakeX == foodX && snakeY == foodY) {
            

            let last = this.snake.snakeObj[this.snake.snakeObj.length - 1]

            this.snake.snakeObj.push({
                x: last.x, 
                y : last.y, 
                color: last.color, 
                el:null            
               
            })
            this.snake.create() //重新绘制蛇
           
            this.food.move()  
          
            this.start() // 开启定时器
            
        }
        // 边界限制，蛇不能超过盒子
        if (snakeX<0||snakeY<0||snakeX>780||snakeY>380){
            alert("游戏结束")
            clearInterval(this.t)
        }
    }, 200)
    

   //点击“停止”按钮，关闭定时器
    Game.prototype.stop = function(){
        clearInterval(this.t)
    }

    // 监控键盘上下左右键 动态更改蛇的direction
    document.addEventListener("keydown", (e) => {

        // 获取事件对象
        e = e || window.event

        // 获取键盘
        switch (e.keyCode) {
            case 38:
                this.snake.direction = "top"
                break;
            case 40:
                this.snake.direction = "bottom"
                break;
            case 37:
                if (this.snake.direction == "right") {
                    alert("游戏结束")
                }
                this.snake.direction = "left"
                break;
            case 39:
                this.snake.direction = "right"
                break;
            default:
                break;
        }
    })
}

